<!--
 * @Author: DT1604\ZPL zhoupeili@dpc.com.cn
 * @Date: 2022-05-28 09:48:37
 * @LastEditors: DT1604\ZPL zhoupeili@dpc.com.cn
 * @LastEditTime: 2022-08-22 10:35:44
 * @FilePath: \energy-om-platform\src\views\cabint\log.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="cmds">
    <el-form :model="form" :rules="rules" ref="form" label-width="120px">
      <el-form
        v-for="(item, index) in form.codeList"
        :key="index"
        :model="item"
        :rules="rules"
        :ref="`form${index}`"
        label-width="120px"
      >
        <el-form-item label="充电柜编码" prop="code">
          <el-input
            style="width: 80%"
            v-model.trim="item.code"
            placeholder="请输入充电柜编码"
            @change.native="keyUp($event, index)"
            @input.native="keyInput($event, index)"
          ></el-input>
          <i
            class="el-icon-delete"
            v-if="index != 0"
            @click="deleteCode(index)"
          ></i>
        </el-form-item>
      </el-form>
      <div class="add_btns">
        <el-button @click.prevent="addCode" type="primary">新增</el-button>
      </div>
      <el-form-item class="dialog-footer">
        <el-button @click="resetForm('form')">取消</el-button>
        <el-button type="primary" @click="confirm" :loading="btnLoading"
          >确定</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { equip } from "@/api/cabint";
export default {
  props: {
    updateDialogVisible: {
      default: true,
      type: Boolean,
    },
    // 设备类型
    equipType: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      form: {
        codeList: [{ code: "" }],
      },
      rules: {
        code: [
          { required: true, message: "请输入充电柜编码", trigger: "blur" },
        ],
      },
      btnLoading: false, //按钮loading
    };
  },
  watch: {
    updateDialogVisible: {
      handler(newVal, oldVal) {
        if (!newVal) {
          this.resetData();
        }
      },
      immediate: true,
    },
  },

  methods: {
    //限制输入特殊字符
    keyUp(e, index) {
      let codes = e.target.value.replace(
        /[`~!@#$%^&*()_\-+=<>?:"{}|,.\;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘’，。、]/g,
        ""
      );
      e.target.value = codes;
      
      if(index != undefined) this.form.codeList[index].code = codes;
    },
    // 只能输入汉字、英文、数字
    keyInput(e,index) {
      let str = e.target.value.replace(/[^\a-\z\A-\Z0-9/]/g, "");
      e.target.value = str;
      if(index != undefined) this.form.codeList[index].code = str;
    },
    addCode() {
      this.form.codeList.push({ code: "" });
    },
    deleteCode(index) {
      this.form.codeList.splice(index, 1);
    },
    resetData() {
      this.resetForm("form");
      this.form = {
        codeList: [{ code: "" }],
      };
      this.btnLoading = false;
    },
    confirm() {
      //用Promise.all进行全部form表单的验证
      Promise.all([
        //非数组部分的表单
        this.validateForm("form"),
        //数组部分的表单，用map返回验证函数的调用
        ...this.form.codeList.map((item, index) =>
          this.validateForm(`form${index}`)
        ),
      ]).then((res) => {
        if (res) {
          // 全部表单验证通过
          this.isDoAdd();
        }
      });
    },
    validateForm(refs) {
      let valiForm = this.$refs?.[refs].validate
        ? this.$refs?.[refs]
        : this.$refs?.[refs][0];
      return new Promise((resolve, reject) => {
        valiForm.validate((res) => {
          if (res) resolve();
          else reject();
        });
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.emitClose();
    },
    // 通知关闭弹框
    emitClose() {
      this.$emit("closeDialog");
    },

    async doAdd() {
      this.btnLoading = true;
      
      let codes = this.form.codeList.map((item) => {
        return item.code;
      });
      let codeparm = codes.length == 1 ? codes.join() : codes.join(",");
      await equip(
        `/batch/insert`,
        "post",
        {
          codes: codeparm,
          equipmentType: this.equipType,
        },
        2
      )
        .then((res) => {
          if (res.code == 200) {
            this.$message({
              message: res.message,
              type: "success",
            });
            this.emitClose();
            this.$emit("resetData");
          }
        })
        .finally((complete) => {
          this.btnLoading = false;
        });
    },
    isDoAdd() {
      this.$confirm("是否确认要批量新增?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.doAdd();
      });
    },
  },
};
</script>

<style scoped lang="scss">
.dialog-footer {
  text-align: right;
  margin-top: 100px;
}
.el-icon-delete {
  font-size: 20px;
  margin-left: 10px;
  color: red;
}
.add_btns {
  margin-left: 120px;
}
</style>
